// 创建Vue组件对象
const apiCall = Vue.component('Api-Call', {
    template: '<div style="text-align: left" class="unSelected">\n' +
        '    <el-drawer :with-header="false" title="API在线测试" :visible.sync="drawer" :direction="direction" size="40%">\n' +
        '      <div style="display: flex;flex-direction: column;align-items: center">\n' +
        '        <div style="width: 90%;margin: 10px">\n' +
        '        </div>\n' +
        '        <div style="width: 90%;margin: 10px;">\n' +
        '          <span>Environment:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>\n' +
        '          <el-radio style="margin-left: -5px" v-for="(item,index) in envs" @change="changeEnviron" :key="index"\n' +
        '                    v-model="current_env" :label="item.idEnv" :disabled="!item.available">\n' +
        '            {{ item.name }}\n' +
        '          </el-radio>\n' +
        '          <br> <br>\n' +
        '          <span style="width: 160px">Request Path:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>\n' +
        '          <div style="width: 100%;display: flex;flex-direction: row">\n' +
        '            <el-input readonly v-model="fullPath"/>\n' +
        '            <el-button style="margin-left: -1px" type="primary" @click="request">Request</el-button>\n' +
        '          </div>\n' +
        '          <span style="display: inline-block;width: 160px;margin-top: 12px">Method:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{\n' +
        '              method\n' +
        '            }}</span>\n' +
        '          <br>\n' +
        '          <el-tabs v-model="activeName">\n' +
        '            <el-tab-pane label="Headers" name="first">\n' +
        '              <div style="display: flex;flex-direction: row;margin-top: 1px">\n' +
        '                <div style="width: 100%;">\n' +
        '                  <div v-for="(item,index) in request_header" :key="index" style="display: flex;flex-direction: row">\n' +
        '                    <el-autocomplete\n' +
        '                        style="margin-top: -1px;"\n' +
        '                        class="inline-input"\n' +
        '                        :fetch-suggestions="headQuerySearch"\n' +
        '                        v-model="item.key"\n' +
        '                        placeholder="请输入内容"/>\n' +
        '                    <el-input placeholder="Value"\n' +
        '                              style="font-size: 14px;margin-top: -1px;margin-left: -1px"\n' +
        '                              v-model="item.value" class="input-with-select">\n' +
        '                      <el-button style="" slot="append" @click="unIncreaseHeader(index)"><i\n' +
        '                          class="delHeads el-icon-minus"/>\n' +
        '                      </el-button>\n' +
        '                      <el-button style="" slot="append" @click="increaseHeaders"><i class="addHeads el-icon-plus"/>\n' +
        '                      </el-button>\n' +
        '                    </el-input>\n' +
        '                  </div>\n' +
        '\n' +
        '                </div>\n' +
        '              </div>\n' +
        '            </el-tab-pane>\n' +
        '            <el-tab-pane label="Parameters" name="second">\n' +
        '              <div style="display: flex;flex-direction: row;margin-top: 1px">\n' +
        '                <div style="width: 100%;">\n' +
        '                  <div v-for="(item,index) in request_param" :key="index">\n' +
        '                    <el-input placeholder="Value"\n' +
        '                              style="font-size: 14px;margin-top: -1px" v-model="item.value"\n' +
        '                              class="input-with-select">\n' +
        '                      <input v-model="item.key" placeholder="Key" style="font-size: 14px" slot="prepend"\n' +
        '                             class="headers-inp"/>\n' +
        '                      <el-button style="" slot="append" @click="unIncreaseParam"><i class="delPara el-icon-minus"/>\n' +
        '                      </el-button>\n' +
        '                      <el-button style="" slot="append" @click="increaseParam"><i class="addPara el-icon-plus"/>\n' +
        '                      </el-button>\n' +
        '                    </el-input>\n' +
        '                  </div>\n' +
        '                </div>\n' +
        '              </div>\n' +
        '            </el-tab-pane>\n' +
        '            <el-tab-pane label="Body" name="third">\n' +
        '              <el-input v-model="bodyJson" type="textarea" rows="5"/>\n' +
        '            </el-tab-pane>\n' +
        '          </el-tabs>\n' +
        '          <span style="display: inline-block;margin-top: 12px;width: 160px;padding-bottom: 1px">Status code：\n' +
        '              <span\n' +
        '                  style="border-radius: 50%;display: inline-block;width: 11px;height: 11px;" :style="statusColor"/>&nbsp;&nbsp;{{\n' +
        '              code\n' +
        '            }}\n' +
        '          </span>\n' +
        '          <br>\n' +
        '          <span\n' +
        '              style="display: inline-block;margin-top: 12px;width: 160px;padding-bottom: 1px">Consuming：{{\n' +
        '              timestamp\n' +
        '            }} ms</span><br>\n' +
        '          <div style="width: 100%;display: flex;flex-direction: row;justify-content: space-between;margin-top: 12px;">\n' +
        '            <span style="display: inline-block;width: 160px;padding-bottom: 1px">Response：</span>\n' +
        '            <span style="font-size: 13px;color: #409EFF;font-weight: bold;cursor: pointer" @click="exportTestExample"><i class="el-icon-download"/>\n' +
        '              Export test example</span>\n' +
        '          </div>\n' +
        '          <JsonViewer style="margin-top: 10px;margin-bottom: 10px;height: auto" v-model="resultJson" copyable boxed :expand-depth="depth"/> \n' +
        '        </div>\n' +
        '      </div>\n' +
        '    </el-drawer>\n' +
        '  </div>',
    data() {
        return {
            fullPath: '',
            data: null,
            bodyJson: '{}',
            activeName: 'first',
            code: 0,
            resultJson: '{}',
            depth: 3,
            timestamp: 0,
            drawer: false,
            direction: 'rtl',
            environment: "",
            envs: [],
            current_env: "",
            input3: '',
            select: '',
            method: "None",
            type: 'https://',
            host: '',
            path: '',
            port: '',
            statusColor: {"background": "#d5d5d5"},
            request_header: [{'key': 'Content-type', 'value': 'application/json'}],
            request_param: [{'key': '', 'value': ''}],
            restaurants: [{"value": "gateway-token"}, {"value": "Content-type"}],
            currentEnvironment: '',
        }
    }, methods: {
        exportTestExample() {
            this.$message.warning("正在开发中")
        },
        request() {
            this.$loading()
            const headers = {};
            this.request_header.forEach(item => {
                if (item.key !== null && item.key !== "" && item.key !== undefined &&
                    item.value !== null && item.value !== "" && item.value !== undefined) {
                    headers[item.key] = item.value;
                }
            })
            let path = this.buildQueryPara();
            let startTime = Date.now()
            if (this.method === "GET") {
                axios.get(this.fullPath + path, {headers: headers}).then(res => {
                    this.resultJson = res.data
                    this.code = res.status
                    if (this.code === 200) {
                        this.statusColor.background = "greenyellow"
                    }
                    this.$loading().close()
                    let end = Date.now()
                    this.timestamp = (end - startTime)
                }).catch(e => {
                    this.$loading().close()
                    this.resultJson = e.response.data
                    this.code = e.response.status
                    this.statusColor.background = "red"
                    let end = Date.now()
                    this.timestamp = (end - startTime)
                })
            } else {
                axios.post(this.fullPath + path, this.bodyJson, {headers: headers}).then(res => {
                    this.resultJson = res.data
                    this.code = res.status
                    if (this.code === 200) {
                        this.statusColor.background = "greenyellow"
                    }
                    this.$loading().close()
                    let end = Date.now()
                    this.timestamp = (end - startTime)
                }).catch(e => {
                    this.$loading().close()
                    this.resultJson = e.response.data
                    this.code = e.response.status
                    this.statusColor.background = "red"
                    let end = Date.now()
                    this.timestamp = (end - startTime)
                })
            }
        },
        buildQueryPara() {
            let para = this.request_param;
            let path = "";
            para.forEach(item => {
                if (path === "")
                    path += "?"
                else
                    path += "&"
                path += item.key
                path += "="
                path += item.value
            })
            return path
        },
        headQuerySearch(queryString, cb) {
            let restaurants = this.restaurants;
            let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        createFilter(queryString) {
            return (restaurant) => {
                return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        increaseHeaders() {
            this.request_header.push({'key': '', 'value': ''})
        },
        increaseParam() {
            this.request_param.push({'key': '', 'value': ''})
        },
        unIncreaseHeader(index) {
            if (this.request_header.length > 1) {
                this.request_header.splice(index, 1)
            }
        },
        unIncreaseParam(index) {
            if (this.request_param.length > 1) {
                this.request_param.splice(index, 1)
            }
        },
        changeEnviron() {
            this.envs.forEach(item => {
                if (item.idEnv === this.current_env) {
                    this.fullPath = this.type.toLowerCase() + item.address + ":" + item.port + this.path
                }
            })
        }, getEnv() {
            this.current_env = ""
            this.envs = []
            axios.get(window.RT_ENV.host_config.host + "/api/env/list").then(res => {
                this.envs = res.data.data
                let ini = []
                for (let i = 0; i < this.envs.length; i++) {
                    if (this.currentEnvironment.indexOf(this.envs[i].idEnv) !== -1) {
                        ini.push(this.envs[i])
                        if (this.current_env === undefined || this.current_env === null || this.current_env === "") {
                            this.current_env = this.envs[i].idEnv
                            this.fullPath = this.type.toLowerCase() + this.envs[i].address + ":" + this.envs[i].port + this.path
                        }
                    }
                }
                this.envs = ini;
            }).catch(e => {
                console.log(e)
                this.$message.error("Get multi-environment node exception")
            })
        },
    }, mounted() {
        this.getEnv()
    },
    watch: {
        data(o1) {
            console.log("Received o1:", o1);
            this.method = o1.method
            this.type = o1.type + "://"
            this.host = "nieva.cn"
            this.port = "443/gateway"
            this.path = o1.path
            this.fullPath = o1.type.toLowerCase() + this.host + ":" + this.port + o1.path

            let process = JSON.parse(o1.process)
            this.currentEnvironment = o1.env
            this.getEnv()
            this.bodyJson = process.jsonParam
            if (process.queryParam !== undefined && process.queryParam !== "" && process.queryParam !== null) {
                let param = []
                process.queryParam.forEach(str => {
                    let jsonObject = JSON.parse(JSON.stringify(str))
                    param.push(jsonObject)
                })
                this.request_param = param
            }
        }
    }
});
